package com.richdown.movie.aop;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.richdown.movie.manager.UserManager;
import com.richdown.movie.model.UserInfo;
import com.richdown.movie.util.JerseyHttpClientUtil;
import com.richdown.movie.util.LoadConfig;

/**
 * 登陆拦截器
 * 
 * @author dinglinan
 * 
 */
public class WebSessionActionImpl implements WebSessionAction {
	private static final Logger logger = LoggerFactory
			.getLogger(WebSessionActionImpl.class);
	@Autowired
	private LoadConfig loadConfig;
	@Autowired
	private UserManager userManager;

	@Override
	public boolean findAnnotation(HttpServletRequest request,
			HttpServletResponse response, Object o, WebSession webSession)
			throws Exception {

		// 在此配置对Class级Session会话的判断拦截
		logger.debug("findAnnotation");

		if (webSession.requestType() == WebSession.RequestType.WEB) {
			logger.debug(webSession.value());
			// 如果值为false则不需要判断会话
			if (StringUtils.equalsIgnoreCase(webSession.value(), "false"))
				return true;

			logger.debug("---=== session filter ===---");

			if (isLogined(request)) {
				request.setAttribute("isLogin", true);
				return true;
			} else {
				request.setAttribute("isLogin", false);
				response.sendRedirect("/");
				return false;
				// return true;//开发用
			}

		} else if (webSession.requestType() == WebSession.RequestType.AJAX) {
			return true;
		} else
			return true;

		// 在此配置对Class级Session会话的判断拦截
/*		logger.debug("findAnnotation");

		if (webSession.requestType() == WebSession.RequestType.WEB) {
			logger.debug(webSession.value());
			// 如果值为false则不需要判断会话
			if (StringUtils.equalsIgnoreCase(webSession.value(), "false"))
				return true;

			if (null == WebUtils.getSessionAttribute(request, "sessioninfo")) {
				response.sendRedirect("/index.jsp");
				return false;
			} else {
				return true;
			}
		} else if (webSession.requestType() == WebSession.RequestType.AJAX) {
			return true;
		} else
			return true;*/
	}

	/**
	 * 判断cookie和session是否存在
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public boolean isLogined(HttpServletRequest request) throws Exception {
		boolean cookieExist = false;
		boolean sessionExist = false;

		/** 判断Cookie是否存在 */
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (".ASPXAUTH".equalsIgnoreCase(cookie.getName())) { // 用户已登录
					// 设置状态为用户已登录
					cookieExist = true;
					break;
				}
			}
		}
		/** 判断session是否存在 */
		HttpSession session = request.getSession();
		sessionExist = session.getAttribute("userInfo") == null ? false : true;

		if (!cookieExist && sessionExist) {// 用户未登录或者注销，销毁session中的用户信息
			session.removeAttribute("userInfo");
		}
		if (cookieExist && !sessionExist) {// cookie存在但还未写session
			String cookieValue = "";
			for (Cookie cookie : cookies) {
				if (".ASPXAUTH".equalsIgnoreCase(cookie.getName())) { // 用户已登录
					cookieValue = cookie.getValue();
					break;
				}
			}
			// String uid="201668592";
			String uid = this.getFetionUserId(cookieValue);
			UserInfo userInfo = new UserInfo();
			userInfo.setUid(uid);
			userInfo = userManager.getFetionUserInfo(userInfo);
			session.setAttribute("userInfo", userInfo);
			sessionExist = true;
		}
		return cookieExist && sessionExist;
	}

	/**
	 * 获取飞信用户uid
	 */
	public String getFetionUserId(String aspxauth) {

		String decryptAspxauth = "";
		// 解密cookie加密串，获取uid
		try {

			decryptAspxauth = JerseyHttpClientUtil.httpPost(
					loadConfig.getCookieUrl(), "authcookie=" + aspxauth,
					"application/x-www-form-urlencoded");
		} catch (Exception e) {
			logger.error("解密cookie串出现错误" + e);
			e.printStackTrace();
		}
		/**
		 * 分隔解密后的cookie串，以逗号分隔 例如103572,200090542,560099724,560099724
		 * 各项定义：网站内部id,核心系统的userId,用户原始飞信号,用户当前飞信号
		 **/
		if (!"".equals(decryptAspxauth)) {
			String[] aspxauthValues = decryptAspxauth.split(",", -1);
			logger.debug("aspxauthValues=" + aspxauthValues.toString());
			if (aspxauthValues.length == 4) {
				String uid = aspxauthValues[1];
				// if (uid.length() == 9) {
				return uid;
				// }
			}
		}
		return "";
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"spring.xml");
		LoadConfig loadConfig = (LoadConfig) context.getBean("loadConfig");
		UserManager um = (UserManager) context.getBean(UserManager.class);
		System.out.println("adfadf");

	}
}
